package gwtadmin.server;


import javax.servlet.http.HttpServlet;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;

public class Activator implements BundleActivator {
	
	private HttpService httpService;
	
	private HttpServlet updoServlet;
	private HttpServlet greetServlet;
	
	private ServiceRegistry registry;
	
	private final String PATH_RSRC = "/registry/rsrc";
	private final String PATH_MYWEBADMIN = "/registry/mywebadmin";
	private final String PATH_TOOL = "/registry/gwt-admin";
	private final String PATH_GREET = "/registry/mywebadmin/greet";
	private final String PATH_UPDO = "/registry/mywebadmin/updo";
	
	private final String PARAM_HTTP_PORT = "org.osgi.service.http.port";
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {

		System.out.println("Starting Registry Web UI");
		
		ServiceReference svcRef = context.getServiceReference(HttpService.class.getName());
		httpService = (HttpService) context.getService(svcRef);
		
		if (httpService == null)
			return;
		
		httpService.registerResources(PATH_RSRC, "/war/rsrc", null);
		httpService.registerResources(PATH_MYWEBADMIN, "/war/mywebadmin", null);
		httpService.registerResources(PATH_TOOL, "/war/MyWebAdmin.html", null);
		
		String port = System.getProperty(PARAM_HTTP_PORT);
		if (port.equals("")) port = "9001";

		registry = new ServiceRegistry("localhost:" + port);
		
		updoServlet = new UpdoServlet(registry);
		greetServlet = new GreetingServiceImpl(registry);
		
		httpService.registerServlet(PATH_GREET, greetServlet, null, null);
		httpService.registerServlet(PATH_UPDO, updoServlet, null, null);
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		System.out.println("Goodbye cruel world, I'm leaving you today");
		
		httpService.unregister(PATH_GREET);
		httpService.unregister(PATH_UPDO);
		httpService.unregister(PATH_MYWEBADMIN);
		httpService.unregister(PATH_TOOL);
		httpService.unregister(PATH_RSRC);
	}
}

